package com.code.statistics.services.impl;

import com.code.statistics.daos.DictMapper;
import com.code.statistics.models.Dict;
import com.code.statistics.services.DictService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 字典业务实现类
 *
 * @author xiaoyaowang
 */
@Service
public class DictServiceImpl implements DictService {

    @Resource
    private DictMapper dictMapper;

    @Override
    public String getDictValueByDictKey(String dictKey) {
        return dictMapper.getDictValueByDictKey(dictKey);
    }

    @Override
    @Transactional(transactionManager = "testTransactionManager", rollbackFor = Exception.class)
    public int patchUpdateDictByDictKeys(List<Dict> dictList) {
        List<Dict> addList = dictList.stream().filter(item -> "0".equals(item.getRemark())).collect(Collectors.toList());
        List<Dict> updateList = dictList.stream().filter(item -> "1".equals(item.getRemark())).collect(Collectors.toList());
        int count = 0;
        if (!CollectionUtils.isEmpty(addList)) {
            count += dictMapper.insertList(addList);
        }
        if (!CollectionUtils.isEmpty(updateList)) {
            count += dictMapper.patchUpdateDictByDictKeys(updateList);
        }
        return count;
    }

    @Override
    public Boolean whetherExistDictKey(String dictKey) {
        return null != dictMapper.whetherExistDictKey(dictKey);
    }

}
